package com.myblog.controller;


import cn.hutool.core.map.MapUtil;
import com.myblog.common.lang.Result;
import com.myblog.entity.Blog;
import com.myblog.entity.Comment;
import com.myblog.service.BlogService;
import com.myblog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author From:星羽恒
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    BlogService blogService;

    @PostMapping("/save")
    public Result saveComment(@RequestBody Comment comment){
        Long count = Long.parseLong(((Integer)commentService.count()).toString());
        comment.setId(count+1);
        commentService.saveOrUpdate(comment);
        return Result.succ(comment);
    }

    @GetMapping("/delete")
    public Result deleteComment(@RequestParam Long id){
        commentService.removeById(id);
        return Result.succ(id);
    }

    @GetMapping("/allComments")
    public Result getAllComments(){
        List<Comment> commentList = commentService.list();

        //根据评论列表，获得文章标题的对应信息
        Map<Long,String> cmtTitleMap = new HashMap<>();
        for(Comment tempCmt : commentList){
            String title = blogService.getById(tempCmt.getBlogId()).getTitle();
            cmtTitleMap.put(tempCmt.getId(),title);
        }

        return Result.succ(MapUtil.builder()
                    .put("commentList",commentList)
                    .put("cmtTitleMap",cmtTitleMap)
                    .map());
    }
}
